<script setup lang="ts">
import { ref, onMounted, onUnmounted, h, computed, nextTick, watch } from 'vue';
import {
  NCard,
  NSpace,
  NDataTable,
  NButton,
  NSelect,
  NTag,
  NIcon,
  NDatePicker,
  NInput,
  useMessage,
  type DataTableColumns,
  type PaginationProps,
  NSwitch,
  NDrawer,
  NDrawerContent,
  NDescriptions,
  NDescriptionsItem,
  NDivider,
  NPopover
} from 'naive-ui';
import { $t } from '@/locales';
import { useStorage } from '@vueuse/core';
import { useThrottleFn } from '@vueuse/core';
import { fetchSystemLogs } from '@/service/api';
import type { PaginationInfo } from 'naive-ui/es/pagination/src/interface';
import type { RenderPrefix } from 'naive-ui/es/pagination/src/interface';

// 日志级别选项
interface LogLevelOption {
  label: string;
  value: LogLevel;
  color: string;
  icon: string;
}

const logLevels = computed<LogLevelOption[]>(() => [
  { label: $t('page.systemLog.level.verbose'), value: 'Verbose', color: 'grey', icon: 'information-line' },
  { label: $t('page.systemLog.level.debug'), value: 'Debug', color: 'blue', icon: 'bug-line' },
  { label: $t('page.systemLog.level.information'), value: 'Information', color: 'green', icon: 'information-fill' },
  { label: $t('page.systemLog.level.warning'), value: 'Warning', color: 'orange', icon: 'alert-line' },
  { label: $t('page.systemLog.level.error'), value: 'Error', color: 'red', icon: 'error-warning-line' },
  { label: $t('page.systemLog.level.fatal'), value: 'Fatal', color: 'magenta', icon: 'alert-fill' }
]);

// 转换为下拉框选项
const levelOptions = computed(() => logLevels.value.map(level => ({
  label: level.label,
  value: level.value,
  type: 'group' as const
})));

// 添加日志限制常量
const LOG_LIMIT = 1000;

// 使用 Record 类型
type LogLevel = Api.SystemLog.LogLevel;
type LevelOrder = Record<LogLevel, number>;
type SortOrder = 'ascend' | 'descend' | false;
type TableSortOrder = 'asc' | 'desc';

const message = useMessage();
const isRequestPending = ref(false);
const logs = ref<Api.SystemLog.LogEntry[]>([]);
const currentLog = ref<Api.SystemLog.LogEntry | null>(null);
const pollingInterval = ref<number | null>(null);
const isPolling = ref(false);

// 分页配置
const pagination = ref<PaginationProps>({
  page: 1,
  pageSize: 50,
  pageCount: 1,
  showSizePicker: true,
  pageSizes: [20, 50, 100, 200],
  itemCount: 0,
  showQuickJumper: false,
  prefix: ((info: PaginationInfo) => $t('page.systemLog.pagination.total', { count: info.itemCount })) as RenderPrefix
});

// 自动滚动控制
const autoScroll = ref(true);
const tableRef = ref<InstanceType<typeof NDataTable> | null>(null);

// 计算当前页数据
const currentPageData = computed(() => {
  const page = pagination.value?.page || 1;
  const pageSize = pagination.value?.pageSize || 50;
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  return logs.value.slice(start, end);
});

// 添加统计接口定义
interface LogStatsType {
  total: number;
  isLimited: boolean;
  [key: string]: number | boolean;
}

// 添加总条数记录
const totalCount = ref(0);

// 修改日志统计计算属性
const logStats = computed<LogStatsType>(() => {
  const stats = {
    total: totalCount.value,
    isLimited: totalCount.value >= LOG_LIMIT
  } as LogStatsType;

  // 初始化所有日志级别的计数为0
  logLevels.value.forEach(level => {
    stats[level.value] = 0;
  });

  // 统计每个级别的日志数量
  logs.value.forEach(log => {
    const level = log.level;
    if (typeof stats[level] === 'number') {
      stats[level] = (stats[level] as number) + 1;
    }
  });

  return stats;
});

// 日志详情抽屉
const showLogDetail = ref(false);

// 搜索历史记录
const searchHistory = useStorage<string[]>('log-search-history', []);
const showSearchHistory = ref(false);

// 快速筛选按钮的选中状态
const selectedLevels = ref<LogLevel[]>([]);

// 搜索条件
const searchConditions = ref({
  dateRange: null as [number, number] | null,
  keyword: '' as string,
  sortField: 'timestamp' as string,
  sortOrder: 'desc' as TableSortOrder
});

// 表格列定义
const columns = computed<DataTableColumns<Api.SystemLog.LogEntry>>(() => {
  return [
    {
      title: $t('page.systemLog.table.time'),
      key: 'timestamp',
      width: 180,
      fixed: 'left',
      defaultSortOrder: 'descend',
      sorter: true,
      sortOrder: 'timestamp' === searchConditions.value.sortField ? 
        (searchConditions.value.sortOrder === 'asc' ? 'ascend' : 'descend') as SortOrder : 
        false,
      render(row) {
        return h('div', {
          class: 'timestamp-cell'
        }, [
          h('div', { class: 'date' }, new Date(row.timestamp).toLocaleDateString()),
          h('div', { class: 'time' }, new Date(row.timestamp).toLocaleTimeString())
        ]);
      }
    },
    {
      title: $t('page.systemLog.table.level'),
      key: 'level',
      width: 100,
      sorter: true,
      sortOrder: 'level' === searchConditions.value.sortField ? 
        (searchConditions.value.sortOrder === 'asc' ? 'ascend' : 'descend') as SortOrder : 
        false,
      render(row) {
        const level = logLevels.value.find(l => l.value === row.level);
        return h(
          NSpace,
          { align: 'center', justify: 'center', size: 4 },
          {
            default: () => [
              h(NIcon, null, {
                default: () => h('i', { class: `ri-${level?.icon}` })
              }),
              h(
                NTag,
                {
                  type: 'info',
                  color: { color: level?.color || 'grey', textColor: '#fff' }
                },
                { default: () => row.level }
              )
            ]
          }
        );
      }
    },
    {
      title: $t('page.systemLog.table.source'),
      key: 'sourceContext',
      width: 160,
      sorter: true,
      sortOrder: 'sourceContext' === searchConditions.value.sortField ? 
        (searchConditions.value.sortOrder === 'asc' ? 'ascend' : 'descend') as SortOrder : 
        false
    },
    {
      title: $t('page.systemLog.table.message'),
      key: 'message',
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: $t('page.systemLog.table.requestInfo'),
      key: 'requestInfo',
      width: 200,
      render(row) {
        if (!row.requestId && !row.requestPath) return null;
        return h('div', { class: 'request-info' }, [
          row.requestId ? h('div', { class: 'request-id' }, `ID: ${row.requestId}`) : null,
          row.requestPath ? h('div', { class: 'request-path' }, row.requestPath) : null
        ]);
      }
    },
    {
      title: $t('page.systemLog.table.exception'),
      key: 'exception',
      ellipsis: {
        tooltip: true
      }
    }
  ];
});

// 更新分页信息
function updatePagination() {
  if (pagination.value.pageSize) {
    pagination.value.pageCount = Math.ceil(totalCount.value / pagination.value.pageSize);
  }
}

// 处理分页变化
function handlePageChange(page: number) {
  if (pagination.value) {
    pagination.value.page = page;
  }
  if (!autoScroll.value) {
    scrollToTop();
  }
}

// 处理每页条数变化
function handlePageSizeChange(pageSize: number) {
  if (pagination.value) {
    pagination.value.pageSize = pageSize;
    pagination.value.page = 1;
  }
  updatePagination();
}

// 修改自动滚动相关的代码
const isUserScrolling = ref(false);
let scrollTimer: number | null = null;
const tableBodyRef = ref<HTMLElement | null>(null);

// 获取表格容器引用
function getTableBody() {
  if (!tableRef.value) return null;
  const element = (tableRef.value as any).$el as HTMLElement;
  if (element) {
    tableBodyRef.value = element.querySelector('.n-data-table-base-table-body');
  }
  return tableBodyRef.value;
}

// 滚动到顶部
const scrollToTop = useThrottleFn((smooth = false) => {
  const tableBody = getTableBody();
  if (tableBody) {
    tableBody.scrollTo({
      top: 0,
      behavior: smooth ? 'smooth' : 'instant'
    });
  }
}, 100);

// 处理表格滚动
function handleTableScroll(e: Event) {
  const tableBody = e.target as HTMLElement;
  if (!tableBody) return;

  // 清除之前的定时器
  if (scrollTimer) {
    window.clearTimeout(scrollTimer);
  }

  // 如果用户向下滚动超过100px，关闭自动滚动
  if (tableBody.scrollTop > 100) {
    autoScroll.value = false;
  }

  // 如果滚动到顶部或接近顶部，开启自动滚动
  if (tableBody.scrollTop <= 50) {
    autoScroll.value = true;
  }
}

// 查看日志详情
function viewLogDetail(log: Api.SystemLog.LogEntry) {
  currentLog.value = log;
  showLogDetail.value = true;
}

// 修改获取日志数据的函数
async function fetchLogs() {
  // 如果有请求正在进行中，则跳过本次请求
  if (isRequestPending.value) {
    return;
  }

  try {
    isRequestPending.value = true;
    const response = await fetchSystemLogs({
      pageSize: pagination.value.pageSize,
      pageIndex: pagination.value.page,
      sortField: searchConditions.value.sortField,
      sortOrder: searchConditions.value.sortOrder,
      levels: selectedLevels.value.length > 0 ? selectedLevels.value : undefined,
      keyword: searchConditions.value.keyword || undefined,
      startTime: searchConditions.value.dateRange?.[0] ? Math.floor(searchConditions.value.dateRange[0] / 1000) : undefined,
      endTime: searchConditions.value.dateRange?.[1] ? Math.floor(searchConditions.value.dateRange[1] / 1000) : undefined
    });

    if (!response?.data) {
      throw new Error($t('page.systemLog.message.fetchFailed'));
    }

    logs.value = response.data.items.map(item => {
      const logEntry: Api.SystemLog.LogEntry = {
        timestamp: item.timestamp,
        level: item.level as LogLevel,
        message: item.message,
        sourceContext: item.sourceContext,
        eventId: item.eventId,
        requestId: item.requestId,
        requestPath: item.requestPath,
        connectionId: item.connectionId,
        exception: item.exception,
        properties: item.properties || {}
      };
      return logEntry;
    });

    // 更新总条数
    totalCount.value = response.data.total;
    pagination.value.itemCount = totalCount.value;
    pagination.value.pageCount = Math.ceil(totalCount.value / (pagination.value.pageSize || 50));

    if (autoScroll.value && pagination.value.page === 1) {
      nextTick(() => {
        const tableBody = getTableBody();
        if (tableBody) {
          tableBody.scrollTo({ top: 0, behavior: 'instant' });
        }
      });
    }
  } catch (error) {
    console.error($t('page.systemLog.message.fetchError'), error);
    message.error($t('page.systemLog.message.getFailed'));
  } finally {
    isRequestPending.value = false;
    if (!isPolling.value) return;
    pollingInterval.value = window.setTimeout(fetchLogs, 1000);
  }
}

// 修改轮询开始函数
function startPolling() {
  stopPolling();
  isPolling.value = true;
  fetchLogs(); // 立即执行一次
}

// 修改轮询停止函数
function stopPolling() {
  isPolling.value = false;
  if (pollingInterval.value) {
    clearTimeout(pollingInterval.value);
    pollingInterval.value = null;
  }
}

// 修改清空日志函数
function clearLogs() {
  logs.value = [];
  totalCount.value = 0;
  updatePagination();
  message.success($t('page.systemLog.message.clearSuccess'));
  // 立即获取新数据
  fetchLogs();
}

// 修改导出日志函数
function exportLogs() {
  try {
    // 构建日志文本内容
    const logContent = logs.value.map(log => {
      const timestamp = new Date(log.timestamp).toLocaleString();
      const level = log.level.padEnd(11);
      const source = log.sourceContext.padEnd(30);
      const message = log.message;
      const eventId = log.eventId ? `\n    ${$t('page.systemLog.export.eventId')}: ${log.eventId}` : '';
      const requestInfo = log.requestId || log.requestPath ? 
        `\n    ${$t('page.systemLog.export.requestInfo')}: ${[
          log.requestId ? `${$t('page.systemLog.export.requestId')}: ${log.requestId}` : '',
          log.requestPath ? `${$t('page.systemLog.export.requestPath')}: ${log.requestPath}` : ''
        ].filter(Boolean).join(', ')}` : '';
      const connectionId = log.connectionId ? `\n    ${$t('page.systemLog.export.connectionId')}: ${log.connectionId}` : '';
      const exception = log.exception ? `\n    ${$t('page.systemLog.export.exception')}:\n${log.exception}` : '';
      const properties = Object.keys(log.properties).length > 0 ? 
        `\n    ${$t('page.systemLog.export.properties')}:\n    ${Object.entries(log.properties)
          .map(([key, value]) => `${key}: ${value}`)
          .join('\n    ')}` : '';

      return `[${timestamp}] ${level} ${source} ${message}${eventId}${requestInfo}${connectionId}${exception}${properties}`;
    }).join('\n\n');

    // 添加文件头部信息
    const header = [
      '='.repeat(80),
      $t('page.systemLog.export.title', { time: new Date().toLocaleString() }),
      '='.repeat(80),
      '\n'
    ].join('\n');

    const content = header + logContent;

    // 创建并下载文件
    const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `system_logs_${new Date().toISOString().slice(0, 19).replace(/[:]/g, '-')}.txt`;
    link.click();
    URL.revokeObjectURL(link.href);

    message.success($t('page.systemLog.message.exportSuccess'));
  } catch (error) {
    console.error($t('page.systemLog.message.exportError'), error);
    message.error($t('page.systemLog.message.exportFailed'));
  }
}

// 修改重置筛选条件的函数
function resetFilters() {
  searchConditions.value = {
    dateRange: null,
    keyword: '',
    sortField: 'timestamp',
    sortOrder: 'desc'
  };
  // 清空选中的日志级别
  selectedLevels.value = [];
  pagination.value.page = 1;
  message.success($t('page.systemLog.message.resetSuccess'));
  fetchLogs();
}

// 搜索防抖
const searchDebounce = ref<number | null>(null);
function handleSearch() {
  if (searchDebounce.value) {
    clearTimeout(searchDebounce.value);
  }

  if (searchConditions.value.keyword) {
    addSearchHistory(searchConditions.value.keyword);
  }

  searchDebounce.value = window.setTimeout(() => {
    fetchLogs();
  }, 300);
}

// 复制日志内容
function copyLogContent(log: Api.SystemLog.LogEntry) {
  const content = [
    `[${new Date(log.timestamp).toLocaleString()}] ${log.level} ${log.sourceContext}`,
    `消息: ${log.message}`,
    log.eventId ? `事件ID: ${log.eventId}` : '',
    log.requestId ? `请求ID: ${log.requestId}` : '',
    log.requestPath ? `请求路径: ${log.requestPath}` : '',
    log.connectionId ? `连接ID: ${log.connectionId}` : '',
    log.exception ? `异常信息:\n${log.exception}` : '',
    Object.keys(log.properties).length > 0 ? `\n其他属性:\n${Object.entries(log.properties).map(([key, value]) => `${key}: ${value}`).join('\n')}` : ''
  ].filter(Boolean).join('\n');

  navigator.clipboard.writeText(content).then(() => {
    message.success($t('page.systemLog.message.copySuccess'));
  }).catch(() => {
    message.error($t('page.systemLog.message.copyFailed'));
  });
}

// 修改处理快速筛选的函数
function handleQuickFilter(level: LogLevelOption) {
  const index = selectedLevels.value.indexOf(level.value);
  if (index > -1) {
    // 取消选中
    selectedLevels.value.splice(index, 1);
  } else {
    // 添加选中
    selectedLevels.value.push(level.value);
  }

  // 重置分页到第一页
  pagination.value.page = 1;

  // 重新获取日志
  fetchLogs();
}

// 添加搜索历史
function addSearchHistory(keyword: string) {
  if (!keyword || searchHistory.value.includes(keyword)) return;
  searchHistory.value.unshift(keyword);
  if (searchHistory.value.length > 10) {
    searchHistory.value.pop();
  }
}

// 使用搜索历史
function useSearchHistory(keyword: string) {
  searchConditions.value.keyword = keyword;
  showSearchHistory.value = false;
  handleSearch();
}

// 清除搜索历史
function clearSearchHistory() {
  searchHistory.value = [];
  message.success($t('page.systemLog.message.clearHistorySuccess'));
}

// 处理表格排序
function handleTableSort(sorter: { columnKey: string, order: SortOrder }) {
  if (!sorter.columnKey || !sorter.order) {
    searchConditions.value.sortField = 'timestamp';
    searchConditions.value.sortOrder = 'desc';
  } else {
    searchConditions.value.sortField = sorter.columnKey;
    searchConditions.value.sortOrder = sorter.order === 'ascend' ? 'asc' : 'desc';
  }
  fetchLogs();
}

// 组件挂载时开始轮询
onMounted(() => {
  startPolling();
});

// 组件卸载时确保清理
onUnmounted(() => {
  stopPolling();
});

// 修改自动滚动开关监听
watch(autoScroll, (newValue) => {
  if (newValue && pagination.value.page === 1) {
    const tableBody = getTableBody();
    if (tableBody) {
      tableBody.scrollTo({ top: 0, behavior: 'instant' });
    }
  }
});
</script>

<template>
  <div class="system-log">
    <NCard>
      <NSpace vertical :size="16">
        <div class="header-section">
          <!-- 日志统计 -->
          <div class="log-stats">
            <NSpace :size="12" align="center">
              <span class="stat-item">
                {{ $t('page.systemLog.stats.total') }}: {{ logStats.total }}
                <NTag v-if="logStats.isLimited" size="small" type="warning">
                  {{ $t('page.systemLog.stats.limitReached') }}
                </NTag>
              </span>
              <NDivider vertical />
              <NSpace :size="8">
                <NPopover
                  v-for="level in logLevels"
                  :key="level.value"
                  trigger="hover"
                  placement="top"
                >
                  <template #trigger>
                    <NTag
                      :color="{ color: level.color, textColor: '#fff' }"
                      size="small"
                      class="level-tag"
                    >
                      <NSpace :size="4" align="center">
                        <NIcon><i :class="`ri-${level.icon}`" /></NIcon>
                        {{ logStats[level.value] }}
                      </NSpace>
                    </NTag>
                  </template>
                  {{ level.label }} 日志
                </NPopover>
              </NSpace>
            </NSpace>
          </div>

          <!-- 操作按钮区域 -->
          <div class="action-buttons">
            <NSpace :size="12">
              <NButton @click="resetFilters" secondary>
                {{ $t('page.systemLog.button.reset') }}
              </NButton>
              <NButton @click="clearLogs" secondary>
                {{ $t('page.systemLog.button.clear') }}
              </NButton>
              <NButton type="primary" @click="exportLogs">
                {{ $t('page.systemLog.button.export') }}
              </NButton>
              <NSwitch
                v-model:value="autoScroll"
                size="small"
              >
                <template #checked>
                  {{ $t('page.systemLog.autoScroll.on') }}
                </template>
                <template #unchecked>
                  {{ $t('page.systemLog.autoScroll.off') }}
                </template>
              </NSwitch>
            </NSpace>
          </div>
        </div>

        <!-- 快速筛选按钮组 -->
        <div class="quick-filters">
          <div class="filter-header">
            <span class="filter-title">{{ $t('page.systemLog.filter.title') }}</span>
            <span class="filter-tip">
              ({{ $t('page.systemLog.filter.tip', {
                selected: selectedLevels.length ? 
                  logLevels.filter(l => selectedLevels.includes(l.value)).map(l => l.label).join(', ') : 
                  $t('page.systemLog.filter.all')
              }) }})
            </span>
          </div>
          <NSpace class="filter-buttons">
            <NButton
              v-for="level in logLevels"
              :key="level.value"
              :type="selectedLevels.includes(level.value) ? 'primary' : 'default'"
              size="small"
              @click="handleQuickFilter(level)"
              :style="{
                borderColor: selectedLevels.includes(level.value) ? level.color : '',
                backgroundColor: selectedLevels.includes(level.value) ? level.color : ''
              }"
            >
              <template #icon>
                <NIcon>
                  <i :class="`ri-${level.icon}`"></i>
                </NIcon>
              </template>
              {{ level.label }}
            </NButton>
          </NSpace>
        </div>

        <!-- 搜索条件区域 -->
        <div class="search-section">
          <NSpace :size="12">
            <NDatePicker
              v-model:value="searchConditions.dateRange"
              type="datetimerange"
              clearable
              :placeholder="$t('page.systemLog.filter.datePlaceholder')"
              class="date-picker"
            />
            <NPopover
              v-model:show="showSearchHistory"
              trigger="click"
              placement="bottom-start"
            >
              <template #trigger>
                <NInput
                  v-model:value="searchConditions.keyword"
                  :placeholder="$t('page.systemLog.search.placeholder')"
                  clearable
                  class="search-input"
                  @keydown.enter="handleSearch"
                >
                  <template #prefix>
                    <NIcon><SvgIcon icon="material-symbols:search" /></NIcon>
                  </template>
                </NInput>
              </template>

              <div class="search-history" v-if="searchHistory.length">
                <div class="search-history-header">
                  <span>{{ $t('page.systemLog.search.history.title') }}</span>
                  <NButton text size="tiny" @click="clearSearchHistory">
                    {{ $t('page.systemLog.search.history.clear') }}
                  </NButton>
                </div>
                <NSpace vertical size="small">
                  <NButton
                    v-for="(item, index) in searchHistory"
                    :key="index"
                    text
                    @click="useSearchHistory(item)"
                  >
                    {{ item }}
                  </NButton>
                </NSpace>
              </div>
            </NPopover>
          </NSpace>
        </div>

        <!-- 数据表格 -->
        <div class="table-section">
          <NDataTable
            ref="tableRef"
            :columns="columns"
            :data="currentPageData"
            :scroll-x="1200"
            :max-height="600"
            :pagination="pagination"
            @update:page="handlePageChange"
            @update:page-size="handlePageSizeChange"
            @update:sorter="handleTableSort"
            @scroll="handleTableScroll"
            :scroll-behavior="autoScroll ? 'instant' : 'auto'"
            striped
            row-class-name="log-row"
            @row-click="viewLogDetail"
          />
        </div>
      </NSpace>
    </NCard>

    <!-- 日志详情抽屉 -->
    <NDrawer
      v-model:show="showLogDetail"
      :width="500"
      placement="right"
    >
      <NDrawerContent
        v-if="currentLog"
        :title="new Date(currentLog.timestamp).toLocaleString()"
      >
        <template #header>
          <div class="drawer-header">
            <span>{{ new Date(currentLog.timestamp).toLocaleString() }}</span>
            <NButton
              secondary
              size="small"
              @click="copyLogContent(currentLog)"
            >
              {{ $t('page.systemLog.button.copy') }}
            </NButton>
          </div>
        </template>
        <NDescriptions :column="1" bordered>
          <NDescriptionsItem :label="$t('page.systemLog.detail.level')">
            <NTag
              :color="{ color: logLevels.find(l => l.value === currentLog?.level)?.color || 'grey' }"
              size="small"
            >
              {{ currentLog?.level }}
            </NTag>
          </NDescriptionsItem>
          <NDescriptionsItem :label="$t('page.systemLog.detail.source')">
            {{ currentLog?.sourceContext }}
          </NDescriptionsItem>
          <NDescriptionsItem v-if="currentLog?.eventId" :label="$t('page.systemLog.detail.eventId')">
            {{ currentLog.eventId }}
          </NDescriptionsItem>
          <NDescriptionsItem v-if="currentLog?.requestId || currentLog?.requestPath" :label="$t('page.systemLog.detail.requestInfo')">
            <div v-if="currentLog.requestId">{{ $t('page.systemLog.detail.requestId') }}: {{ currentLog.requestId }}</div>
            <div v-if="currentLog.requestPath">{{ $t('page.systemLog.detail.requestPath') }}: {{ currentLog.requestPath }}</div>
          </NDescriptionsItem>
          <NDescriptionsItem v-if="currentLog?.connectionId" :label="$t('page.systemLog.detail.connectionId')">
            {{ currentLog.connectionId }}
          </NDescriptionsItem>
          <NDescriptionsItem :label="$t('page.systemLog.detail.message')">
            {{ currentLog?.message }}
          </NDescriptionsItem>
          <NDescriptionsItem v-if="currentLog?.exception" :label="$t('page.systemLog.detail.exception')">
            <NDivider />
            <pre class="exception-detail">{{ currentLog.exception }}</pre>
          </NDescriptionsItem>
          <NDescriptionsItem v-if="Object.keys(currentLog?.properties || {}).length > 0" :label="$t('page.systemLog.detail.properties')">
            <NDivider />
            <div v-for="(value, key) in currentLog?.properties" :key="key" class="property-item">
              <strong>{{ key }}:</strong> {{ value }}
            </div>
          </NDescriptionsItem>
        </NDescriptions>
      </NDrawerContent>
    </NDrawer>
  </div>
</template>

<style scoped>
.system-log {
  padding: 16px;
  height: 100%;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.log-stats {
  padding: 12px 16px;
  border-radius: 6px;
  border: 1px solid var(--n-border-color);
  background-color: var(--n-color-light);
}

.level-tag {
  transition: transform 0.2s ease;
  cursor: pointer;
}

.level-tag:hover {
  transform: translateY(-2px);
}

.quick-filters {
  margin: 16px 0;
  padding: 16px;
  border-radius: 6px;
  border: 1px solid var(--n-border-color);
  background-color: var(--n-color-light);
}

.filter-header {
  margin-bottom: 12px;
}

.filter-buttons {
  gap: 8px;
}

.search-section {
  padding: 16px;
  border-radius: 6px;
  border: 1px solid var(--n-border-color);
  background-color: var(--n-color-light);
}

.level-select {
  width: 180px;
}

.date-picker {
  width: 380px;
}

.search-input {
  width: 240px;
}

.table-section {
  border-radius: 6px;
  border: 1px solid var(--n-border-color);
  background-color: var(--n-color-light);
  padding: 16px;
}

/* 优化表格滚动条样式 */
.system-log :deep(.n-data-table-base-table-body) {
  scrollbar-width: thin;
  scrollbar-color: var(--n-scrollbar-color) transparent;
}

.system-log :deep(.n-data-table-base-table-body::-webkit-scrollbar) {
  width: 6px;
  height: 6px;
}

.system-log :deep(.n-data-table-base-table-body::-webkit-scrollbar-thumb) {
  background-color: var(--n-scrollbar-color);
  border-radius: 3px;
}

.system-log :deep(.n-data-table-base-table-body::-webkit-scrollbar-track) {
  background-color: transparent;
}

/* 表格行样式 */
.log-row {
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.log-row:hover {
  background-color: var(--n-table-color-hover) !important;
}

/* 新日志项的动画 */
@keyframes newLog {
  from {
    background-color: rgba(var(--n-primary-color-rgb), 0.1);
  }
  to {
    background-color: transparent;
  }
}

.system-log :deep(.n-data-table-tr:first-child) {
  animation: newLog 2s ease-out;
}

/* 其他样式保持不变 */
.system-log :deep(.n-data-table-tr) {
  transition: all 0.3s ease-in-out;
}

.system-log :deep(.n-input) {
  transition: all 0.3s;
}

.system-log :deep(.n-input:hover),
.system-log :deep(.n-input:focus) {
  box-shadow: 0 0 0 2px rgba(var(--n-primary-color-rgb), 0.1);
}

.system-log :deep(.n-button) {
  transition: all 0.3s;
}

.system-log :deep(.n-button:not(:last-child)) {
  margin-right: 8px;
}

.system-log :deep(.n-switch) {
  margin-left: 12px;
}

.exception-detail {
  margin: 0;
  padding: 12px;
  border-radius: 4px;
  font-family: monospace;
  white-space: pre-wrap;
  word-break: break-all;
  font-size: 12px;
  line-height: 1.5;
  color: var(--n-text-color-2);
}

:deep(.n-drawer-content) {
  padding: 16px;
}

.request-info {
  font-size: 12px;
}

.request-id {
  color: var(--n-text-color-2);
  margin-bottom: 4px;
}

.request-path {
  color: var(--n-text-color-3);
  word-break: break-all;
}

.property-item {
  margin: 8px 0;
  font-size: 12px;
}

.property-item strong {
  color: var(--n-text-color-2);
  margin-right: 8px;
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 14px 18px;
  border-bottom: 1px solid var(--n-border-color);
}
</style>
